
<html>
    <head><title>Script de configuración</title></head>
    <body>
        <h3>Aplicación</h3>
        <table border="1">
            <tbody>
                <tr>
                    <th scope="row">CHARSET</th><td><?= CHARSET ?></td>
                </tr>
                <tr>
                    <th scope="row">USE_SYMLINKS</th><td><?= USE_SYMLINKS ?></td>
                </tr>
                <tr>
                    <th scope="row">ASYNCHRONOUS</th><td><?= ASYNCHRONOUS ?></td>
                </tr>
            </tbody>
        </table>
        <h3>Directorios</h3>
        <table border="1">
            <tbody>
                <tr>
                    <th scope="row">SERVER APP PATH</th><td><?= PATH ?></td>
                </tr>
                <tr>
                    <th scope="row">SERVER ROOT PATH</th><td><?= SERVER_ROOT_PATH ?></td>
                </tr>
                <tr>
                    <th scope="row">WEB FOLDER</th><td><?= CO_PROJECO_INDEX ?></td>
                </tr>
            </tbody>
        </table>
        <h3>Base de Datos</h3>
        <table border="1">
            <tbody>
                <tr>
                    <th scope="row">DB_HOST</th><td><?= DB_HOST ?></td>
                </tr>
                <tr>
                    <th scope="row">DB_PORT</th><td><?= DB_PORT ?></td>
                </tr>
                <tr>
                    <th scope="row">DB_USER</th><td><?= DB_USER ?></td>
                </tr>
                <tr>
                    <th scope="row">DB_DB</th><td><?= DB_DB ?></td>
                </tr>
                <tr>
                    <th scope="row">DB_CHARSET</th><td><?= DB_CHARSET ?></td>
                </tr>
            </tbody>
        </table>
        <h3>Cache</h3>
        <table border="1">
            <tbody>
                <tr>
                    <th scope="row">HTML_MEMCACHE_ENABLED</th><td><?= HTML_MEMCACHE_ENABLED ?></td>
                </tr>
                <tr>
                    <th scope="row">HTML_MEMCACHE_TIME</th><td><?= HTML_MEMCACHE_TIME ?></td>
                </tr>
                <tr>
                    <th scope="row">SMALL_SLOW_QUERIES</th><td><?= SMALL_SLOW_QUERIES ?></td>
                </tr>
                <tr>
                    <th scope="row">POLICIES_SHM_ENABLED</th><td><?= POLICIES_SHM_ENABLED ?></td>
                </tr>
                <tr>
                    <th scope="row">POLICIES_SHM_SIZE</th><td><?= POLICIES_SHM_SIZE ?></td>
                </tr>
                <tr>
                    <th scope="row">POLICIES_MEMCACHE_ENABLED</th><td><?= POLICIES_MEMCACHE_ENABLED ?></td>
                </tr>
                <tr>
                    <th scope="row">POLICIES_MEMCACHE_TIME</th><td><?= POLICIES_MEMCACHE_TIME ?></td>
                </tr>
                <tr>
                    <th scope="row">SOAP_CACHE</th><td><?= SOAP_CACHE ?></td>
                </tr>
            </tbody>
        </table>
        <h3>Debug</h3>
        <table border="1">
            <tbody>
                <tr>
                    <th scope="row">ROLLBACK_ERRORS</th><td><?= ROLLBACK_ERRORS ?></td>
                </tr>
                <tr>
                    <th scope="row">ERROR_REPORTING</th><td><?= error_reporting() ?></td>
                </tr>
            </tbody>
        </table>
        <?php
        set_time_limit( 120 );
        error_reporting( E_STRICT | E_ALL );
        require 'zero_core/Deployment.class.php';


//Deployment::init(); //ahora tenemos en POLICY_NAMES y POLICY_IDS los valores antiguos
        $nodeIDS = Deployment::$POLICIES_IDS;
        if ( empty( $nodeIDS ) ) $nodeIDS = array( );

        $min = 0;
        while ( in_array( $min, $nodeIDS ) )
            $min++;

        $CONFIG = array( );
        $CONFIG[ Deployment::POLICY_NAME ] = array( );
        $CONFIG[ Deployment::POLICY_TYPE ] = array( );
        $CONFIG[ Deployment::TEMPLATE_STAGE ] = array( );
        if ( USE_SYMLINKS ) $CONFIG[ Deployment::CLASS_PATH ] = array( );

//$autoload='';
//Primero debería buscar todas las clases en cada uno de los directorios a partir del artual
        $classpath = array( );
        $intefaces = array( );

        function buscarFicheros( $ruta )
        {
            global $CONFIG, $classpath, $interfaces, $nodeIDS; //$autoload

            if ( $gestor = opendir( $ruta ) ) {

                $archivo = readdir( $gestor );

                while ( $archivo !== false ) {

                    if ( $archivo !== '.' && $archivo !== '..' ) {
                        $ruta_archivo = $ruta . DIRECTORY_SEPARATOR . $archivo;

                        $coincidencias = array( );

                        if ( is_dir( $ruta_archivo ) && $ruta_archivo != '.' . DIRECTORY_SEPARATOR . '0' && $ruta_archivo != '0' )
                                buscarFicheros( $ruta_archivo );

                        else if ( preg_match( '/^([A-Z].*)\.([^.]+)\.php$/',
                                        $archivo, $coincidencias ) ) {
//coincidencias[1] es le nombre de la clase

                            if ( $coincidencias[ 2 ] != 'class' ) {

                                if ( !isset( $CONFIG[ Deployment::TEMPLATE_STAGE ][ $coincidencias[ 1 ] ] ) )
                                        $CONFIG[ Deployment::TEMPLATE_STAGE ][ $coincidencias[ 1 ] ] = array(
                                            );

                                //if(USE_SYMLINKS)
                                //  $CONFIG[Deployment::TEMPLATE_STAGE][$coincidencias[1]][$coincidencias[2]]=true;
                                //  else
                                $CONFIG[ Deployment::TEMPLATE_STAGE ][ $coincidencias[ 1 ] ][ $coincidencias[ 2 ] ] = substr( $ruta_archivo,
                                        2,
                                        -strlen( '.' . $coincidencias[ 2 ] . '.php' ) );
                            }
                            else { //if(USE_SYMLINKS){ //tengo que almacenarlo en la de classes
                                $cont = file_get_contents( $ruta_archivo );
                                if ( !preg_match( '/\n\s*class\s+' . $coincidencias[ 1 ] . '\s*[\s\n\{]/',
                                                $cont ) && !preg_match( '/\n\s*abstract\s+class\s+' . $coincidencias[ 1 ] . '\s*[\s\n\{]/',
                                                $cont ) ) {
                                    echo 'File ' . $ruta_archivo . ' doesn\'t have the class  ' . $coincidencias[ 1 ] . ' defined inside';
                                    throw new Exception( 'File ' . $ruta_archivo . ' doesn\'t have the class  ' . $coincidencias[ 1 ] . ' defined inside' );
                                }

                                //$classpath[$coincidencias[1]]=substr($ruta_archivo,2,-strlen('/'.$coincidencias[1].'.class.php'));
                                $classpath[ $coincidencias[ 1 ] ] = substr( $ruta_archivo,
                                        2,
                                        -strlen( $coincidencias[ 1 ] . '.class.php' ) );
                            }
                        } else if ( substr( $archivo, -4 ) === '.xml' ) {
                            $politica = substr( $archivo, 0, -4 );
                            $xml = simplexml_load_file( $ruta_archivo );

                            if ( $xml && isset( $xml->policy ) ) {

                                if ( isset( $interfaces[ $politica ] ) ) {
                                    throw new Exception( 'Existen dos XML para el nodo ' . $politica );
                                } else {

                                    if ( isset( $nodeIDS[ $politica ] ) )
                                            $CONFIG[ Deployment::POLICY_NAME ][ $nodeIDS[ $politica ] ] = $politica;
                                    else {

                                        while ( in_array( $min, $nodeIDS ) )
                                            $min++;

                                        $CONFIG[ Deployment::POLICY_NAME ][ $min ] = $politica;
                                        $min++;
                                    }


                                    $interfaces[ $politica ] = $ruta_archivo;
                                }
                            }
                        }
                    }

                    $archivo = readdir( $gestor );
                }

                closedir( $gestor );
            }
        }

        buscarFicheros( '.' );


        if ( !USE_SYMLINKS ) $CONFIG[ Deployment::CLASS_PATH ] = $classpath;

        $madres = array( );
        try {
            foreach ( $classpath as $n => $info ) {

                $madre = get_parent_class( $n ); //en una clase sin clase madre que me devuelve? null?
                $madres[ $n ] = $madre;

                if ( is_subclass_of( $n, 'Node' ) ) {
                    if ( USE_CLASS_POLICIES ) {
                        if ( isset( $nodeIDS[ $n ] ) ) {
                            $CONFIG[ Deployment::POLICY_NAME ][ $nodeIDS[ $n ] ] = $n;
                            $CONFIG[ Deployment::POLICY_TYPE ][ $nodeIDS[ $n ] ] = Node::ISCLASS;
                        } else {

                            while ( in_array( $min, $nodeIDS ) )
                                $min++;

                            $CONFIG[ Deployment::POLICY_NAME ][ $min ] = $n;
                            $CONFIG[ Deployment::POLICY_TYPE ][ $min ] = Node::ISCLASS;
                            $min++;
                        }
                    }
                }
            }
        } catch ( Exception $e ) {
            echo $e;
        }

        $arbol = array( );
        $nodos = array( );

        function buscarHijas( $clase, &$array )
        {
            global $madres, $nodos;

            foreach ( $madres as $c => $madre ) {
                if ( $madre == $clase ) {
                    $array[ $c ] = array( );
                    $nodos[ $c ] = true;
                    buscarHijas( $c, $array[ $c ] );
                }
            }
        }

        foreach ( $madres as $c => $madre ) {
            if ( $madre === 'Node' ) {
                $arbol[ $c ] = array( );
                $nodos[ $c ] = true;
                buscarHijas( $c, $arbol[ $c ] );
            }
        }
        ?>
        <h3>Árbol de Clases</h3>
        <pre>
            <?php
            var_dump( $arbol );
            ?>
        </pre>

        <?

        function heredarTemplates( $arbol )
        {
            global $CONFIG;

            foreach ( $arbol as $madre => $hijas ) {
                $nomhijas = array_keys( $hijas );

                if ( isset( $CONFIG[ Deployment::TEMPLATE_STAGE ][ $madre ] ) ) {
                    //para cada uno de los stage y la ruta a la plantilla

                    if ( count( $CONFIG[ Deployment::TEMPLATE_STAGE ][ $madre ] ) > 0 ) { //tiene que tener el class y al menos uno mas para que hereden algo las hijas
                        foreach ( $CONFIG[ Deployment::TEMPLATE_STAGE ][ $madre ] as
                                    $stage => $file ) {

                            //para cada una de las clases hijas
                            //  if($stage!=='class'){ //si las hijas no tienen un stage class no podrían ser hijas
                            foreach ( $nomhijas as $nom ) {
                                if ( !isset( $CONFIG[ Deployment::TEMPLATE_STAGE ][ $nom ] ) )
                                        $CONFIG[ Deployment::TEMPLATE_STAGE ][ $nom ] = array(
                                            );

                                if ( !isset( $CONFIG[ Deployment::TEMPLATE_STAGE ][ $nom ][ $stage ] ) )
                                        $CONFIG[ Deployment::TEMPLATE_STAGE ][ $nom ][ $stage ] = $file;
                            }
                            //}
                        }
                    }
                }

                heredarTemplates( $hijas );
            }
        }

        heredarTemplates( $arbol );


        MyLink::$default = new MyLink( DB_HOST, DB_USER, DB_PASS, DB_DB,
                DB_PORT, DB_CHARSET ); //???





        $engine = 'InnoDB';
        $engines = MyLink::$default->get_rows( 'SHOW ENGINES', true );
        foreach ( $engines as $e ) {

            if ( ( strtolower( $e[ 0 ] ) == 'ndbcluster' ) && $e[ 1 ] != 'DISABLED' && $e[ 1 ] != 'NO' )
                    $engine = $e[ 0 ];
        }

        if ( strtolower( $engine ) == 'ndbcluster' ) {
            //Debido a que no hay tablas temporales

            $sql = 'CREATE TABLE IF NOT EXISTS `borrar_aristas` (
`id` int(11) DEFAULT NULL
) ENGINE=ndbcluster DEFAULT CHARSET=latin1';
            MyLink::$default->execute( $sql );

            $sql = 'CREATE TABLE IF NOT EXISTS `borrar_aristas_aux` (
 `id` int(11) DEFAULT NULL
) ENGINE=ndbcluster DEFAULT CHARSET=latin1';
            MyLink::$default->execute( $sql );
        }

//debería pensar en lugar de utilizar esta tabla mantenerlo en SESSION de forma que se reduzcan estos accesos a la BD
        $sql = 'CREATE TABLE IF NOT EXISTS `security_cache_blocks` (
 `grupo` int(11) NOT NULL,
 `nodo` int(5) NOT NULL,
 `clase` varbinary(50) NOT NULL,
 PRIMARY KEY (`grupo`,`nodo`)
) ENGINE=' . $engine . ' DEFAULT CHARSET=latin1';
        MyLink::$default->execute( $sql );

//TABLAS DE CACHES DE RECURSOS;
        $sql = 'CREATE TABLE IF NOT EXISTS `oak_security_contexts` (
 `context_id` int(11) NOT NULL AUTO_INCREMENT,
 `md5` binary(32) NOT NULL,
 `serialization` blob NOT NULL,
 PRIMARY KEY (`context_id`),
 KEY `md5` (`md5`)
) ENGINE=' . $engine . ' DEFAULT CHARSET=latin1';
        MyLink::$default->execute( $sql );

        $sql = 'CREATE TABLE IF NOT EXISTS `security_cache_resources` (
 `grupo` int(11) NOT NULL,
 `nodo` int(5) NOT NULL,
 `idCampo` varbinary(255) NOT NULL,
 `idNumerico` varbinary(127) NOT NULL,
 `indiceClase` tinyblob NOT NULL,
 `sql` blob NOT NULL,
 `fin` varbinary(127) NOT NULL,
 PRIMARY KEY (`grupo`,`nodo`)
) ENGINE=' . $engine . ' DEFAULT CHARSET=latin1';
        MyLink::$default->execute( $sql );

        $sql = 'CREATE TABLE IF NOT EXISTS `security_edges` (
 `Id` int(11) NOT NULL AUTO_INCREMENT,
 `VerticeInicio` varchar(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 `VerticeInicioId` int(50) NOT NULL,
 `VerticeFin` varchar(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 `VerticeFinId` int(50) NOT NULL,
 `IdAristaEntrada` int(11) DEFAULT NULL,
 `IdAristaSalida` int(11) DEFAULT NULL,
 `Implicita` enum(\'S\',\'N\') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 `Contexto` varchar(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 PRIMARY KEY (`Id`)
) ENGINE=' . $engine . ' DEFAULT CHARSET=latin1';
        MyLink::$default->execute( $sql );

        $sql = 'CREATE TABLE IF NOT EXISTS `security_privileges` (
 `Id` int(11) NOT NULL AUTO_INCREMENT,
 `Rol` varchar(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 `RolId` int(50) NOT NULL,
 `Recurso` varchar(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 `RecursoId` int(50) NOT NULL,
 `Clase` varchar(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 PRIMARY KEY (`Id`),
 KEY `Rol` (`Rol`,`Recurso`)
) ENGINE=' . $engine . ' DEFAULT CHARSET=latin1';
        MyLink::$default->execute( $sql );

        $sql = 'CREATE TABLE IF NOT EXISTS `security_roles` (
 `User` int(11) NOT NULL,
 `Rol` varchar(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
 `RolId` int(50) NOT NULL,
 PRIMARY KEY (`User`,`Rol`,`RolId`)
) ENGINE=' . $engine . ' DEFAULT CHARSET=latin1';
        MyLink::$default->execute( $sql );

        $sql = 'CREATE TABLE IF NOT EXISTS `security_users` (
 `user` int (10) NOT NULL,
 `last` timestamp NOT NULL default CURRENT_TIMESTAMP,
 `group` int(11) NOT NULL,
 PRIMARY KEY  (`user`)
) ENGINE=' . $engine . ' DEFAULT CHARSET=latin1';
        MyLink::$default->execute( $sql );

        $sql = 'CREATE TABLE IF NOT EXISTS `security_users_accesses` (
 `user` int(10) NOT NULL,
 `ip` varchar(15) NOT NULL,
 `sid` varchar(50) NOT NULL,
 `first` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `last` timestamp NOT NULL DEFAULT \'0000-00-00 00:00:00\',
 `suspect` enum(\'Y\',\'N\') CHARACTER SET ascii NOT NULL DEFAULT \'N\'
) ENGINE=' . $engine . ' DEFAULT CHARSET=latin1';
        MyLink::$default->execute( $sql );


//BORRAMOS LAS CACHES
        $sql = 'TRUNCATE TABLE security_cache_resources';
        MyLink::$default->execute( $sql );

        $sql = 'TRUNCATE TABLE security_cache_blocks';
        MyLink::$default->execute( $sql );

        $sql = 'UPDATE security_cache_groups SET FullRolStr=\'\'';
        MyLink::$default->execute( $sql );



        Deployment::resetMemory(); //reiniciamos la memoria por si hemos cambiado el tamaño



        if ( USE_SYMLINKS ) {

            foreach ( $classpath as $class => $path ) {
                symlink( PATH . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $class . '.class.php',
                        CF_CONFIG_PATH . $class . '.class.php' );

                if ( !file_exists( CF_CONFIG_PATH . $class . '.class.php' ) )
                        echo 'Unabled to create ' . CF_CONFIG_PATH . $path . $class . '.class.php' . '  -> ' . CF_CONFIG_PATH . $class . '.class.php<br />';
                else
                        echo PATH . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $class . '.class.php' . '  -> ' . CF_CONFIG_PATH . DIRECTORY_SEPARATOR . $class . '.class.php<br />';
            }


            foreach ( $CONFIG[ Deployment::TEMPLATE_STAGE ] as $class => &$stgs ) {
                foreach ( $stgs as $s => &$file ) {
                    symlink( PATH . DIRECTORY_SEPARATOR . $file . '.' . $s . '.php',
                            CF_CONFIG_PATH . $class . '.' . $s . '.php' );

                    if ( !file_exists( CF_CONFIG_PATH . $class . '.' . $s . '.php' ) )
                            echo 'Unabled to create ' . PATH . DIRECTORY_SEPARATOR . $file . '.' . $s . '.php' . '  -> ' . CF_CONFIG_PATH . $class . '.' . $s . '.php<br />';
                    else
                            echo PATH . DIRECTORY_SEPARATOR . $file . '.' . $s . '.php' . '  -> ' . CF_CONFIG_PATH . $class . '.' . $s . '.php<br />';

                    $file = true;
                }
            }
        }



        $tablas = array( );
        $r = MyLink::$default->get_rows( 'SHOW TABLES', true )->toArray();
        $NUMTYPES = array( 'INTEGER', 'SMALLINT', 'DECIMAL', 'NUMERIC', 'FLOAT',
            'REAL', 'DOUBLE PRECISION', 'INT', 'DEC', 'TINYINT', 'MEDIUMINT', 'BIGINT',
            'BIT' );

        foreach ( $r as $row ) {

            $tablas[ $row ] = array( );
            $res = MyLink::$default->get_rows( 'SHOW COLUMNS FROM `' . $row . '`',
                            true )->toArray();


            foreach ( $res as $re ) {
                list($columna, $tipo, $nula, $key, $default, $extra) = $re;
                $pos = strpos( $tipo, '(' );
                if ( $pos !== 0 ) $tipo = substr( $tipo, 0, $pos );

                $tablas[ $row ][ $columna ] = in_array( strtoupper( trim( $tipo ) ),
                        $NUMTYPES );
            }
        }

        unset( $r, $row, $res, $pos, $tipo, $columna, $nula, $key, $default,
                $extra, $NUMTYPES, $link );
        ?>
        <h3>Tablas de la Base de Datos</h3>
        <table border="1">
            <thead>
                <tr><th>Nombre</th><th>Columnas</th></tr>
            </thead>
            <tbody>
                <?php
                foreach ( $tablas as $nombre => $colsRnums ):
                    ?>
                    <tr><td><?= $nombre ?></td><td>
                            <?php
                            foreach ( $colsRnums as $col => $isNum ):
                                ?>
                                <?= $col . ($isNum ? '*' : '') ?>,
                            <?php endforeach; ?>
                        </td></tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr><td colspan="2">* columnas numéricas</td></tr>
            </tfoot>
        </table>
        <?php
        unset( $nombre, $colsRnums, $isNum, $col );

//Para que sea usable antes del PHP 5.0.3 dónde se permite que el primer parametro de is_subclass_of
//OJO
        /*    function buscarInterface($ruta) {
          global $interfaces, $nodeIDS, $min, $CONFIG;

          if ($gestor = opendir($ruta)) {

          $archivo = readdir($gestor);

          while ($archivo != false) {

          if ($archivo !== '.' && $archivo !== '..') {
          $ruta_archivo = $ruta . '/' . $archivo;


          if (substr($archivo, -4) === '.xml') {
          $clase = substr($archivo, 0, -4);


          if (isset($interfaces[$clase])) {
          throw new Exception('Existen dos XML para el nodo ' . $clase);
          } else {

          if (isset($nodeIDS[$clase]))
          $CONFIG[Deployment::POLICY_NAME][$nodeIDS[$clase]] = $clase;
          else {

          while (in_array($min, $nodeIDS))
          $min++;
          $CONFIG[Deployment::POLICY_NAME][$min] = $clase;
          $min++;
          }


          $interfaces[$clase] = $ruta_archivo;
          }
          } else if (is_dir($ruta_archivo))
          buscarInterface($ruta_archivo);

          unset($coincidencias, $ruta_archivo);
          }

          $archivo = readdir($gestor);
          }

          closedir($gestor);
          unset($gestor, $archivo);
          }
          }



          $interfaces = array();
         */


        //              buscarInterface('.'.DIRECTORY_SEPARATOR.'policies'); //Aqui establecesmos Deployment::$POLICIES_IDS
//Ahora tengo que añadir las clases a nodesId




        foreach ( $interfaces as $class => $path )
                $interfaces[ $class ] = obtenerInterface( $class, $path );
        ?>





        <?php
//TENGO QUE HACER HEREDAR TODAS LAS PLANTILLAS



        $policyIDS = array_flip( $CONFIG[ Deployment::POLICY_NAME ] );

        $nodeTypes = array( );
        foreach ( $interfaces as $policy => $inter ) {
            $id = $policyIDS[ $policy ];


            //LAS CLASES PROTEGIDAS POR ALGUNA POLITICA NO DEFINEN POLITICA POR DEFECTO, NI ELLAS NI SUS PADRES

            $CONFIG[ Deployment::POLICY_TYPE ][ $id ] = $inter[ 0 ];
            if ( $inter[ 0 ] == Node::ISRESOURCE ) {
                foreach ( $inter[ 1 ][ 'classes' ] as $c => $sqk ) {

                    while ( $c != 'Node' ) {
                        if ( isset( $policyIDS[ $c ] ) && isset( $CONFIG[ Deployment::POLICY_TYPE ][ $policyIDS[ $c ] ] ) ) {
                            unset( $CONFIG[ Deployment::POLICY_TYPE ][ $policyIDS[ $c ] ] );
                            unset( $CONFIG[ Deployment::POLICY_NAME ][ $policyIDS[ $c ] ] );
                        }

                        $c = get_parent_class( $c );
                    }
                }
            } else {
                foreach ( $inter[ 1 ] as $inf ) {
                    $c = $inf[ 'class' ];

                    while ( $c != 'Node' ) {
                        if ( isset( $policyIDS[ $c ] ) && isset( $CONFIG[ Deployment::POLICY_TYPE ][ $policyIDS[ $c ] ] ) ) {
                            unset( $CONFIG[ Deployment::POLICY_TYPE ][ $policyIDS[ $c ] ] );
                            unset( $CONFIG[ Deployment::POLICY_NAME ][ $policyIDS[ $c ] ] );
                        }

                        $c = get_parent_class( $c );
                    }
                }
            }

            Deployment::storePolicy( $id, $inter[ 1 ] );
        }
        Deployment::storeDeployment( $CONFIG );
        /*
          $CNF=array();
          foreach($policyIDS as $pname=>$pid){
          $CNF[$pid]=array();
          $CNF[$pid][Deployment::POLICY_NAME]=$pname;
          $CNF[$pid][Deployment::POLICY_TYPE]=$CONFIG[Deployment::POLICY_TYPE][$pid];

          if($CNF[$pid][Deployment::POLICY_TYPE]==Node::ISCLASS){
          $CNF[$pid][Deployment::TEMPLATE_STAGE]=$CONFIG[Deployment::TEMPLATE_STAGE][$pname];

          if(!USE_SYMLINKS)
          $CNF[$pid][Deployment::CLASS_PATH]=$CONFIG[Deployment::CLASS_PATH][$pname];
          }
          }
          Deployment::storeConfig($CNF);
         */
        ksort( $interfaces );
        ?>

        <h3>Política e ID</h3>
        <pre>
            <?php
            var_dump( $CONFIG[ Deployment::POLICY_NAME ] );
            ?>
        </pre>
        <h3>Interfaces de las politicas</h3>
        <table border="1">
            <thead>
                <tr><th>Policy</th><th>config</th></tr>
            </thead>
            <tbody>
                <?php
                foreach ( $interfaces as $class => $inter ):
                    ?>
                    <tr>
                        <td><?= $class ?></td>
                        <td><pre><?php var_dump( $inter[ 1 ] ) ?></pre></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php

//$get y $post deben estar en los HTMLBlock
        function obtenerInterface( $class, $path )
        {
            global $tablas;

            $xml = simplexml_load_file( $path );

            $type = null;
            $config = null;

            if ( isset( $xml->select ) ) { //Es un ResourceNode
                $type = Node::ISRESOURCE;
                $config = array( );

                $select = explorarSELECT( ( string ) $xml->select[ 'sql' ] );


                //Ahora tengo que ver que me devuelve el select para UsuarioAdminColegioNode

                $config[ 'where' ] = $select[ 'where' ];
                $config[ 'from' ] = $select[ 'from' ];
                $config[ 'base' ] = $select[ 'reserved' ];
                $config[ 'end' ] = $select[ 'end' ];

                foreach ( $select[ 'campos' ] as $alias => $field ) {
                    $c = array( );

                    if ( $alias === 'id' ) {
                        $config[ 'idField' ] = $field;
                        break;
                    } else if ( preg_match( '/^id\[(\d+)\]$/', $alias, $c ) ) {
                        if ( !isset( $config[ 'idField' ] ) || !is_array( $config[ 'idField' ] ) )
                                $config[ 'idField' ] = array( );

                        $config[ 'idField' ][ ( int ) $c[ 1 ] ] = $field;

                        ksort( $config[ 'idField' ] );
                    }
                }

                if ( empty( $config[ 'idField' ] ) )
                        throw new Exception( 'Falta campo con alias id:' . $class );

                //AQUI SI HUBIERA VARIOS idField uno por uno buscaría si es numerico o no
                if ( is_array( $config[ 'idField' ] ) ) {
                    $config[ 'idNumeric' ] = array( );

                    foreach ( $config[ 'idField' ] as $k => $v )
                            $config[ 'idNumeric' ][ $k ] = esNumerico( $v,
                                $select );
                }
                else
                        $config[ 'idNumeric' ] = esNumerico( $config[ 'idField' ],
                            $select );

                $config[ 'fields' ] = array( );
                $config[ 'classes' ] = array( ); //puedo transformar este array en un array indexado por el nombre de la clase y con una sentencia sql como dato

                if ( isset( $xml->policy ) ) {


                    if ( isset( $xml->policy->use[ 1 ] ) ) {
                        foreach ( $xml->policy->use as $u ) {

                            //Aqui tengo que obtener la reflexion de la clase

                            if ( !isset( $config[ 'fields' ][ ( string ) $u[ 'class' ] ] ) ) {

                                $campos = array( );
                                foreach ( $select[ 'campos' ] as $alias =>
                                            $field ) {

                                    if ( preg_match( '/^id\[(\d+)\]$/', $alias ) )
                                            $campos[ $alias ] = $field;

                                    else {
                                        try {
                                            $ref = new ReflectionProperty( ( string ) $u[ 'class' ],
                                                    $alias );
                                            $campos[ $alias ] = $field;
                                        } catch ( Exception $ex ) {
                                            echo 'La clase ' . $u[ 'class' ] . ' no posee la propiedad ' . $alias . ' (' . $class . ')<br />';
                                        }
                                    }
                                }

                                $config[ 'fields' ][ ( string ) $u[ 'class' ] ] = $campos;
                            }

                            $resourcesClass = array( );
                            $sqk = '';
                            if ( isset( $u->sql ) )
                                    $sqk = ( string ) $u->sql[ 'where' ];


                            if ( isset( $u->resource[ 1 ] ) )
                                    foreach ( $u->resource as $r )
                                        $resourcesClass[ ] = array( ( string ) $r[ 'tag' ],
                                        isset( $r[ 'id' ] ) ? ( string ) $r[ 'id' ] : null );

                            else if ( isset( $u->resource ) )
                                    $resourcesClass[ ] = array( ( string ) $u->resource[ 'tag' ],
                                    isset( $u->resource[ 'id' ] ) ? ( string ) $u->resource[ 'id' ] : null );


                            $config[ 'classes' ][ ( string ) $u[ 'class' ] ] = array(
                                'resources' => $resourcesClass, 'where' => $sqk );
                        }
                    }
                    else if ( isset( $xml->policy->use ) ) {


                        if ( !isset( $config[ 'fields' ][ ( string ) $xml->policy->use[ 'class' ] ] ) ) {
                            $campos = array( );
                            //Aqui tengo que establecer los campos a los que tiene acceso
                            foreach ( $select[ 'campos' ] as $alias => $field ) {

                                if ( preg_match( '/^id\[(\d+)\]$/', $alias ) )
                                        $campos[ $alias ] = $field;
                                else {
                                    try {
                                        $ref = new ReflectionProperty( ( string ) $xml->policy->use[ 'class' ],
                                                $alias );
                                        $campos[ $alias ] = $field;
                                    } catch ( Exception $ex ) {
                                        echo 'La clase ' . $xml->policy->use[ 'class' ] . ' no posee la propiedad ' . $alias . ' (' . $class . ')<br />';
                                    }
                                }
                            }

                            //Aqui tb podría utilizar el id de la clase
                            $config[ 'fields' ][ ( string ) $xml->policy->use[ 'class' ] ] = $campos;
                        }

                        //tengo que incorporar todos los where en una cadena concatenada con ANDs y partirla por IN USER_RESOURCES
                        //y todos los roles tb

                        $resourcesClass = array( );
                        $sqk = '';
                        if ( isset( $xml->policy->use->sql ) )
                                $sqk = ( string ) $xml->policy->use->sql[ 'where' ];


                        if ( isset( $xml->policy->use->resource[ 1 ] ) )
                                foreach ( $xml->policy->use->resource as $r )
                                    $resourcesClass[ ] = array( ( string ) $r[ 'tag' ],
                                    isset( $r[ 'id' ] ) ? ( string ) $r[ 'id' ] : null );

                        else if ( isset( $xml->policy->use->resource ) )
                                $resourcesClass[ ] = array( ( string ) $xml->policy->use->resource[ 'tag' ],
                                isset( $xml->policy->use->resource[ 'id' ] ) ? ( string ) $xml->policy->use->resource[ 'id' ] : null );

                        $config[ 'classes' ][ ( string ) $xml->policy->use[ 'class' ] ] = array(
                            'resources' => $resourcesClass, 'where' => $sqk );
                    }
                }

                //OJO IGUAL ME PONEN VARIOS WHERE EN EL USE, ESOS HAY QUE CONCATENARLOS CON UN AND Y ENCERRANDO ENTRE PARENTESIS CADA UNO DE ELLOS
                //LUEGO SE HACE EL EXPLODE
                //tengo que escojer para cada clase los campos que extraer
                $config[ 'selectData' ] = '';

                $campos = array( );

                foreach ( $config[ 'classes' ] as $c => $zql ) {
                    foreach ( $config[ 'fields' ][ $c ] as $alias => $nombre )
                            if ( !in_array( $alias, $campos ) ) {
                            $config[ 'selectData' ].=', ' . $nombre . ' AS `' . $alias . '`';
                            $campos[ ] = $alias;
                        }
                }
            } else if ( isset( $xml->policy ) && isset( $xml->policy->use ) ) {
                $type = Node::ISBLOCK;

                $config = array( );

                if ( isset( $xml->policy->use[ 1 ] ) ) {
                    foreach ( $xml->policy->use as $h ) {


                        $roles = array( );
                        if ( isset( $h->rol[ 1 ] ) ) {
                            foreach ( $h->rol as $w )
                                    $roles[ ] = array( ( string ) $w[ 'tag' ], isset( $w[ 'id' ] ) ? ( string ) $w[ 'id' ] : 0 );
                        } else if ( isset( $h->rol ) )
                                $roles[ ] = array( ( string ) $h->rol[ 'tag' ], isset( $h->rol[ 'id' ] ) ? ( string ) $h->rol[ 'id' ] : 0 );;


                        if ( isset( $h[ 'policy' ] ) )
                                $config[ ] = array( 'class' => ( string ) $h[ 'class' ],
                                'roles' => $roles, 'policy' => ( string ) $h[ 'policy' ] );
                        else
                                $config[ ] = array( 'class' => ( string ) $h[ 'class' ],
                                'roles' => $roles, 'policy' => '' );
                    }
                }
                else if ( isset( $xml->policy->use ) ) {

                    $roles = array( );

                    if ( isset( $xml->policy->use->rol[ 1 ] ) ) {
                        foreach ( $xml->policy->use->rol as $w )
                                $roles[ ] = array( ( string ) $w[ 'tag' ], isset( $w[ 'id' ] ) ? ( string ) $w[ 'id' ] : 0 );
                    } else if ( isset( $xml->policy->use->rol ) )
                            $roles[ ] = array( ( string ) $xml->policy->use->rol[ 'tag' ],
                            isset( $xml->policy->use->rol[ 'id' ] ) ? ( string ) $xml->policy->use->rol[ 'tag' ] : 0 );

                    if ( isset( $xml->policy->use[ 'policy' ] ) )
                            $config[ ] = array( 'class' => ( string ) $xml->policy->use[ 'class' ],
                            'roles' => $roles, 'policy' => ( string ) $xml->policy->use[ 'policy' ] );
                    else
                            $config[ ] = array( 'class' => ( string ) $xml->policy->use[ 'class' ],
                            'roles' => $roles, 'policy' => '' );

                    //$config[] = array('class' => (string) $xml->policy->use['class'], 'roles' => $roles);
                }
            }


            return array( $type, $config );
        }
        ?>
    </body>
</html>
<?php

function esNumerico( $idField, $select )
{
    global $tablas;

    $fil = '';
    $pos = -1;
    $ant = -2;
    while ( $pos !== false ) {
        $fil = substr( $idField, $pos + 1 );
        $tbl = substr( $idField, $ant + 1, $pos - $ant - 1 );
        $ant = $pos;
        $pos = ibuscar( $idField, '.', $pos + 1 );
    }

    if ( $fil[ 0 ] === '`' || $fil[ 0 ] === '\'' ) $fil = substr( $fil, 1, -1 );

    if ( !empty( $tbl ) && ( $tbl[ 0 ] === '`' || $tbl[ 0 ] === '\'') )
            $tbl = substr( $tbl, 1, -1 );


    //Primero compruebo si $tbl es un alias
    if ( $tbl !== '' ) {
        foreach ( $select[ 'tablas' ] as $t ) {
            $pos = -1;
            $tab = '';
            while ( $pos !== false ) {
                $tab = substr( $t[ 'nombre' ], $pos + 1 );
                $pos = ibuscar( $t[ 'nombre' ], '.', $pos + 1 );
            }

            if ( $tab[ 0 ] === '`' || $tab[ 0 ] === '\'' )
                    $tab = substr( $tab, 1, -1 );

            if ( $t[ 'alias' ] !== null && $tbl === $t[ 'alias' ] )
                    return $tablas[ $tab ][ $fil ];
        }

        //Si no es un alias tiene que ser el nombre de una tabla
        foreach ( $select[ 'tablas' ] as $t ) {
            $pos = -1;
            $tab = '';
            while ( $pos !== false ) {
                $tab = substr( $t[ 'nombre' ], $pos + 1 );
                $pos = ibuscar( $t[ 'nombre' ], '.', $pos + 1 );
            }

            if ( $tab[ 0 ] === '`' || $tab[ 0 ] === '\'' )
                    $tab = substr( $tab, 1, -1 );

            if ( $tbl === $tab ) return $tablas[ $tab ][ $fil ];
        }
    }
    else { //si no hay entonces tiene que ser el campo de una de las tablas
        foreach ( $select[ 'tablas' ] as $t ) {
            $pos = -1;
            $tab = '';
            while ( $pos !== false ) {
                $tab = substr( $t[ 'nombre' ], $pos + 1 );
                $pos = ibuscar( $t[ 'nombre' ], '.', $pos + 1 );
            }

            if ( $tab[ 0 ] === '`' || $tab[ 0 ] === '\'' )
                    $tab = substr( $tab, 1, -1 );

            if ( isset( $tablas[ $tab ][ $fil ] ) )
                    return $tablas[ $tab ][ $fil ];
        }
    }

    throw new Exception( 'No se ha encontrado campo ' . $idField );
}

function ibuscar( $cadena, $caracter, $inicio = 0 )
{
    $candena = strtoupper( $cadena );
    $caracter = strtoupper( $caracter );
    $n = strlen( $cadena );

    $c_cadena = array( '\'', '`' );

    $lon = strlen( $caracter );
    $dentro_cadena = null;
    $dentro_parentesis = 0;

    for ( $i = $inicio; $i < $n; ++$i ) {
        $c = $candena[ $i ];

        if ( $dentro_cadena !== null ) {
            if ( $c === $dentro_cadena ) $dentro_cadena = null;
        }
        else if ( $dentro_parentesis > 0 ) {
            if ( $c === '(' ) $dentro_parentesis++;
            else if ( $c === ')' ) $dentro_parentesis--;
            else if ( $c === '\'' || $c === '`' ) $dentro_cadena = $c;
        }
        else if ( isset( $cadena[ $i + $lon ] ) && substr( $cadena, $i, $lon ) === $caracter )
                return $i;

        else if ( $c === '\'' || $c === '`' ) $dentro_cadena = $c;
        else if ( $c === '(' ) $dentro_parentesis = 1;
    }

    return false;
}

function quitarEspacios( $cadena )
{
    $candena = trim( $cadena );
    $cadenanueva = '';
    $anterior = ' ';
    $dentro = false;

    for ( $i = 0, $n = strlen( $cadena ); $i < $n; ++$i ) {
        $c = $cadena[ $i ];

        if ( $dentro ) {
            $cadenanueva.=$c;
            if ( $dentro === $c ) $dentro = false;
        }
        else {
            if ( $c !== ' ' || $anterior !== ' ' && $anterior !== '.' && $anterior !== '(' && $anterior !== ',' )
                    $cadenanueva.=$c;

            if ( $c === '`' || $c === '\'' ) $dentro = $c;
        }

        $anterior = $c;
    }

    $dentro = false;
    $anterior = '.';
    $cadenarenueva = '';

    for ( $i = strlen( $cadenanueva ); $i > 0; --$i ) {
        $c = $cadenanueva[ $i - 1 ];

        if ( $dentro ) {
            $cadenarenueva = $c . $cadenarenueva;
            if ( $dentro === $c ) $dentro = false;
        }
        else {
            if ( $anterior !== '.' && $anterior !== ')' && $anterior !== ',' || $c !== ' ' ) {
                $cadenarenueva = $c . $cadenarenueva;
                $anterior = $c;
            }
            if ( $c === '`' || $c === '\'' ) $dentro = $c;
        }
    }

    return $cadenarenueva;
}

function explorarSELECT( $consulta )
{
    $consulta = str_replace( array( '\r', '\n' ), array( ' ', ' ' ), $consulta );
    $consulta = quitarEspacios( trim( $consulta ) );

    if ( ibuscar( $consulta, 'SELECT' ) !== 0 ) return;

    $struct = array(
        'reserved' => '',
        'campos' => array( ),
        'from' => '',
        'tablas' => array( ),
        'where' => '', //Son las partes del WHERE, con IN USER_RESOURCES de por pormedio
        'end' => ''
    );

    $reservadas = array( 'ALL', 'DISTINCT', 'DISTINCTROW', 'HIGH_PRIORITY', 'STRAIGHT_JOIN',
        'SQL_SMALL_RESULT', 'SQL_BIG_RESULT', 'SQL_BUFFER_RESULT', 'SQL_CACHE', 'SQL_NO_CACHE',
        'SQL_CALC_FOUND_ROWS' );

    $posfrom = ibuscar( $consulta, 'FROM' );
    $poswhere = ibuscar( $consulta, 'WHERE' );
    $posgroup = ibuscar( $consulta, 'GROUP BY' );

    $select = substr( $consulta, 7, $posfrom - 7 - 1 ); //Quito espacios de inicio y fin

    if ( $poswhere !== false ) {
        $struct[ 'from' ] = substr( $consulta, $posfrom + 5,
                $poswhere - $posfrom - 5 - 1 );
        if ( $posgroup !== false ) {
            $struct[ 'where' ] = substr( $consulta, $poswhere + 6,
                    $posgroup - $poswhere - 6 - 1 );
            $struct[ 'end' ] = substr( $consulta, $posgroup );
        }
        else $struct[ 'where' ] = substr( $consulta, $poswhere + 6 );
    }
    else {
        if ( $posgroup !== false ) {
            $struct[ 'from' ] = substr( $consulta, $posfrom + 5,
                    $posgroup - $posfrom - 5 - 1 );
            $struct[ 'end' ] = substr( $consulta, $posgroup );
        }
        else $struct[ 'from' ] = substr( $consulta, $posfrom + 5 );
    }

    //AHORA TENGO QUE VER SI TENGO ALGUNA PALABRA RESERVADA ANTES DE LOS CAMPOS
    //tengo que buscar la primera palabra, si es distinta de alguna de las reservadas significaría que es un campo

    $pos = -1;
    $posespacio = ibuscar( $select, ' ', $pos + 1 );
    while ( $posespacio !== false ) {
        if ( !in_array( strtoupper( substr( $select, $pos + 1,
                                        $posespacio - $pos - 1 ) ), $reservadas ) )
                break;
        else {
            $struct[ 'reserved' ].=' ' . substr( $select, $pos + 1,
                            $posespacio - $pos - 1 );
            $pos = $posespacio;
            $posespacio = ibuscar( $select, ' ', $pos + 1 );
        }
    }
    //$pos está apuntando al último espacio
    //una vez supero las reservadas las demás son campos

    $campos = array( );
    $poscoma = ibuscar( $select, ',', $pos + 1 );
    while ( $poscoma !== false ) {
        $campos[ ] = substr( $select, $pos + 1, $poscoma - $pos - 1 );
        $pos = $poscoma;
        $poscoma = $poscoma = ibuscar( $select, ',', $pos + 1 );
    }
    $campos[ ] = substr( $select, $pos + 1 );

    foreach ( $campos as $c ) {
        //Para cada uno de los campos tengo que buscar el alias o el nombre del campo
        //si hay un espacio en blanco
        $campo = '';
        $alias = '';

        $posespacio = ibuscar( $c, ' ' );

        if ( $posespacio !== false ) {

            $pos = null;
            while ( $posespacio !== false ) {
                $pos = $posespacio;
                $posespacio = ibuscar( $c, ' ', $pos + 1 );
            }

            $alias = substr( $c, $pos + 1 );
            $campo = substr( $c, 0, $pos );
            if ( strtoupper( substr( $campo, -3 ) ) === ' AS' )
                    $campo = substr( $campo, 0, -3 );
        }
        else {
            $campo = $c;
            $pos = -1;
            $pospunto = strpos( $c, '.', $pos + 1 );
            while ( $pospunto !== false ) {
                $pos = $pospunto;
                $pospunto = strpos( $c, '.', $pos + 1 );
            }
            $alias = substr( $c, $pos + 1 );
        }

        //si el alias tiene `` tengo que quitarselas ya que luego se las pongo al construir la SQL
        $coin = array( );
        if ( preg_match( '/^`(.+)`$/', $alias, $coin ) ) $alias = $coin[ 1 ];

        $struct[ 'campos' ][ $alias ] = $campo;
    }


    $reservadas = array( 'INNER', 'CROSS', 'JOIN', 'STRAIGHT_JOIN', 'LEFT', 'OUTER',
        'NATURAL', 'ON', 'RIGHT', 'USE', 'IGNORE', 'FORCE', 'USIGN' );
    $inicio = 0;

    $trozos = explode( ',', $struct[ 'from' ] );
    $trozos_new = array( );

    foreach ( $trozos as $t ) {
        if ( strpos( $t, ' UNION ' ) ) {
            $partes = explode( 'UNION', $t );
            foreach ( $partes as $p ) $trozos_new[ ] = trim( $p );
        }
        else $trozos_new[ ] = trim( $t );
    }

    $trozos = $trozos_new;
    $trozos_new = array( );

    foreach ( $trozos as $t ) {
        if ( strpos( $t, 'JOIN' ) ) {
            $partes = explode( 'JOIN', $t );
            foreach ( $partes as $p ) {
                $pos = strpos( $p, ' ON ' );
                if ( $pos !== false ) {
                    $p = substr( $p, 0, $pos );
                }
                $trozos_new[ ] = trim( $p );
            }
        }
        else $trozos_new[ ] = trim( $t );
    }


    foreach ( $trozos_new as $t ) {
        $coincidencias = array( );
        $tabla = null;
        $alias = null;

        if ( preg_match( '/^([^\s]+)\sAS\s([^\s]+)/iu', $t, $coincidencias ) ) {
            $tabla = $coincidencias[ 1 ];
            $alias = $coincidencias[ 2 ];
        } else if ( preg_match( '/^([^\s]+)\s([^\s]+)/iu', $t, $coincidencias ) ) {
            if ( in_array( $coincidencias[ 2 ], $reservadas ) )
                    $tabla = $coincidencias[ 1 ];

            else {
                $tabla = $coincidencias[ 1 ];
                $alias = $coincidencias[ 2 ];
            }
        }
        else $tabla = $t;

        if ( $tabla[ 0 ] === '`' ) $tabla = substr( $tabla, 1, -1 );

        if ( $alias !== null && $alias[ 0 ] === '`' )
                $alias = substr( $alias, 1, -1 );

        $struct[ 'tablas' ][ ] = array( 'nombre' => $tabla, 'alias' => $alias );
    }

    return $struct;
}
?>